﻿#include "dataanalysiswindow.h"
#include "ui_dataanalysiswindow.h"
#include "mainwindow.h"
#include "qmladvancedanalysisconfig.h"

QMap<QString,QColor> accessColorList;
QMap<QString,QColor> sampleColorList;
int ChartColorType;

DataAnalysisWindow::DataAnalysisWindow(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::DataAnalysisWindow)
{
    ui->setupUi(this);

#ifdef Q_OS_ANDROID
    int fontId = QFontDatabase::addApplicationFont(":/FontStyle/AlibabaPuHuiTi-3-55-Regular.ttf");
    if (fontId != -1) {
        QStringList fontFamilies = QFontDatabase::applicationFontFamilies(fontId);
        if (!fontFamilies.isEmpty()) {
            QString familyName = fontFamilies.first();
            QFont font(familyName, 18);
            QFont smallerFont(familyName, 16);
            this->setFont(smallerFont);
            QList<QWidget*> uiWidgets = ui->pannel->findChildren<QWidget*>();
            foreach(auto uiWidget, uiWidgets){
                uiWidget->setFont(font);
            }
            ui->pushButton_2->setFont(smallerFont);
            ui->pushButton_3->setFont(smallerFont);
            ui->pushButton_6->setFont(smallerFont);
            ui->pushButton_5->setFont(smallerFont);
            ui->pushButton_advanceConfig->setFont(smallerFont);
            ui->pushButton_exportImage->setFont(smallerFont);
            ui->pushButton_back->setFont(smallerFont);
            ui->pushButton_open->setFont(smallerFont);
            font.setBold(true);
            ui->label_title->setFont(font);
        }
    }
#endif

    MainWindow::isRefDataAnalysis = true;

    pState = nullptr;
    _chartManager = nullptr;
    _table = nullptr;
    _tableGuide = nullptr;
    _actionBar = nullptr;

    _dialog_as = nullptr;
    _dialog_filter = nullptr;
    _dialog_ac = nullptr;

#ifdef Q_OS_ANDROID
    ui->pushButton_print->hide();
    ui->pushButton_printAll->hide();
#endif

}

DataAnalysisWindow::~DataAnalysisWindow()
{
    delete ui;
}

void DataAnalysisWindow::resizeEvent(QResizeEvent* event){
    QWidget::resizeEvent(event);
}

void DataAnalysisWindow::on_openfile(QString name){
    ui->label_title_right->setText("当前文件: "+name);
    this->showMaximized();
}


void DataAnalysisWindow::reloadData(){


    DebugLog::funcStart(DEBUG_CONTEXT);



    // 执行数据分析
    if(_boxAnalysis != nullptr){
        delete _boxAnalysis;
        _boxAnalysis = nullptr;
    }

    _boxAnalysis = new QMessageBox(QMessageBox::Question, "提示", "正在执行数据分析,请稍后", QMessageBox::Yes, this);
    _boxAnalysis->show();
    QTimer::singleShot(100, [this](){

        releaseResource();
        ChartColorType=0;

        // 创建组件
        _chartManager = new PCRChartManager(this);
        _table = new PCRTable(QStringList() << "孔位" << "样本名称" << "样本类型" << "荧光染料" << "CT" << "浓度" << "平均浓度", this);
        _tableGuide = new GuideTable(this);
        _actionBar = new PCRActionBar(this);
        pState = new PCRState();

        _dialog_filter = new DialogFilter2(this);
        _dialog_filter->close();
        _dialog_as = new DialogAnalysisSettings(this);
        _dialog_as->close();
        _dialog_ac = new DialogAdvanceConfig(this);
        _dialog_ac->close();

        // 信号绑定
        connect(pState, SIGNAL(sigFilterResultChanged()), _chartManager, SLOT(on_filterResultChanged()));
        connect(pState, SIGNAL(sigBoldResultChanged()),   _chartManager, SLOT(on_boldResultChanged()));

        connect(pState, SIGNAL(sigPageChanged()), _chartManager,    SLOT(on_pageChanged()));
        connect(pState, SIGNAL(sigPageChanged()), _table,           SLOT(on_pageChanged()));
        connect(pState, SIGNAL(sigPageChanged()), _actionBar,       SLOT(on_pageChanged()));
        connect(pState, SIGNAL(sigPageChanged()),  this,            SLOT(on_pageChanged()));
        connect(pState, SIGNAL(sigPageChanged()), _tableGuide,      SLOT(on_pageChanged()));

        connect(pState, SIGNAL(sigFilterChanged()), _table,         SLOT(on_filterChanged()));
        connect(pState, SIGNAL(sigFilterChanged()), _tableGuide,    SLOT(on_filterChanged()));

        connect(pState, SIGNAL(sigThrChanged()), _chartManager,     SLOT(on_thrChanged()));
        connect(pState, SIGNAL(sigThrChanged()), _table,            SLOT(on_thrChanged()));
        connect(pState, SIGNAL(sigThrChanged()), _actionBar,        SLOT(on_thrChanged()));
        connect(pState, SIGNAL(sigThrChanged()), this,              SLOT(on_thrChanged()));

        connect(pState, SIGNAL(sigModelChanged()), _chartManager,   SLOT(on_modelChanged()));
        connect(pState, SIGNAL(sigModelChanged()), _table,          SLOT(on_modelChanged()));
        connect(pState, SIGNAL(sigModelChanged()), _actionBar,      SLOT(on_modelChanged()));

        connect(pState, SIGNAL(sigFilterStart()), this,             SLOT(on_filterStart()));

        connect(pState, SIGNAL(sigStandardChanged()), _table,       SLOT(on_standardChanged()));
        connect(pState, SIGNAL(sigStandardChanged()), _chartManager,SLOT(on_standardChanged()));

        connect(pState, SIGNAL(sigGuideNumChanged()), _actionBar,   SLOT(on_guideNumChanged()));

        connect(pState, SIGNAL(sigGuidePageChanged()), _tableGuide, SLOT(on_guidePageChanged()));
        connect(pState, SIGNAL(sigGuideReCalculate()), _tableGuide, SLOT(on_recalculate()));

        connect(pState, SIGNAL(sigColorChanged()), _actionBar, SLOT(on_colorChanged()));

        connect(_dialog_as->_button_yes, SIGNAL(clicked()), this, SLOT(on_reanalysis()));


        connect(_dialog_ac->component(), SIGNAL(sigReanalysis(QStringList, QMap<QString, double>)), this, SLOT(on_reanalysis_single(QStringList, QMap<QString, double>)));
        connect(_dialog_ac->component(), SIGNAL(sigSelectCurveChanged(QStringList)), this, SLOT(on_configSelectChanged(QStringList)));

        // 界面组件布局初始化
        ui->layout_operation->addWidget(_actionBar);
        //ui->layout_chartLabel->addWidget(_chartLegend);

        ui->layout_chart->addWidget(_chartManager);
        ui->layout_table->addWidget(_table);
        ui->layout_table->addWidget(_tableGuide);


        _tableGuide->hide();

//        if(MainWindow::experimentStatus.get()==4){
//            ui->pushButton_9->show();
//            ui->pushButton_10->show();
//        }else{
//            ui->pushButton_9->hide();
//            ui->pushButton_10->hide();
//        }

        if(MainWindow::experimentStatus.get() == 4){

//            ui->label_title_right->show();
        }else{
//            ui->label_title_right->hide();
            ui->label_title_right->setText("");
        }


        initData();                 // 读取数据
        //datao();
        sampleColorList.clear();
        for (int i=0;i<pState->nameList.length();i++) {
            sampleColorList.insert(pState->nameList[i],QColor(0,136,255));
        }

        accessColorList.clear();
        accessColorList.insert("FAM",QColor(66,  46,  205));
        accessColorList.insert("VIC",QColor(0, 196, 115));
        accessColorList.insert("ROX",QColor(255, 135, 62));
        accessColorList.insert("CY5",QColor(255, 43,  55));

        _boxAnalysis->close();
        _boxAnalysis->hide();
    });

    DebugLog::funcEnd(DEBUG_CONTEXT);

}

void DataAnalysisWindow::showEvent(QShowEvent *event)
{


    DebugLog::write("数据分析showEvent - dataAnalysisWindow line34 ==============");

//    DataAnalysis da; da.datao();  // 自动导出测试

    if( ! MainWindow::isRefDataAnalysis )  return;
    MainWindow::isRefDataAnalysis = false;

    reloadData();
    event->accept();

#ifdef Q_OS_ANDROID
    this->setFixedSize(this->width(), this->height());
#endif
}

void DataAnalysisWindow::on_configSelectChanged(QStringList curveName){
    QStringList res;
    foreach(auto name, curveName){
        if(name != "" && pState->filterResult.contains(name)){
            res.push_back(name);
        }
    }
    pState->boldResult = res;
    pState->emitBoldResultChanged();
}

void DataAnalysisWindow::on_pushButton_9_clicked()
{
    this->close();
    emit changeSampleWindow();
}

void DataAnalysisWindow::on_pushButton_10_clicked()
{
    this->close();
    emit changeExperiInfoWindow();
}

void DataAnalysisWindow::on_pushButton_back_clicked()
{
    this->close();
    MainWindow::isRefDataAnalysis = true;
    if(MainWindow::experimentStatus.get()==4){      // 不知道是干嘛的
        MainWindow::experimentStatus.set(0);
    }

    releaseResource();

    emit changeMainWindow();

}

void DataAnalysisWindow::releaseResource(){
    if(pState)          { delete pState;             pState = nullptr;           }
    if(_chartManager)   { delete _chartManager;      _chartManager = nullptr;    }
    if(_table)          { delete _table;             _table = nullptr;           }
    if(_actionBar)      { delete _actionBar;         _actionBar = nullptr;       }
    if(_tableGuide)     { delete _tableGuide;        _tableGuide = nullptr;      }
    if(_dialog_filter)  { delete _dialog_filter;     _dialog_filter = nullptr;   }
    if(_dialog_as)      { delete _dialog_as;         _dialog_as = nullptr;       }
    if(_dialog_ac)      { delete _dialog_ac;         _dialog_ac = nullptr;       }
}


// 分析配置
void DataAnalysisWindow::on_pushButton_2_clicked(){
//#ifdef Q_OS_ANDROID
//    _dialog_as->exec();
//#else
//    _dialog_as->exec();
//    _dialog_ac->hide();
//    _dialog_filter->hide();

//#endif
        _dialog_as->exec();
        _dialog_ac->hide();
        _dialog_filter->hide();
}

void DataAnalysisWindow::on_reanalysis(){


    _dialog_as->close();
    _dialog_as->on_checkChanged();
    if(_boxAnalysis != nullptr){
        delete _boxAnalysis;
        _boxAnalysis = nullptr;
    }
    _boxAnalysis = new QMessageBox(QMessageBox::Question, "提示", "正在执行数据分析,请稍后", QMessageBox::Yes, this);
    _boxAnalysis->show();
    QTimer::singleShot(100, [this](){
        pState->calModel();
        pState->calCt();
        pState->calStandardCurve();
        pState->emitModelChanged();
        pState->emitPageChanged();
        pState->emitFilterChanged();
        pState->emitFilterResultChanged();
        pState->emitThrChanged();
        _boxAnalysis->close();
        _boxAnalysis->hide();
    });
}

void DataAnalysisWindow::on_reanalysis_single(QStringList curve, QMap<QString, double> params){

    DebugLog::funcStart(DEBUG_CONTEXT);

    QString curveName;
    foreach(QString curveName, curve){
        if(!pState->modelList.contains(curveName)) continue;
        pState->modelList[curveName]->setParam(QPCRModel::Model::FIXED_BASE_END, params["FIXED_BASE_END"]);
        pState->modelList[curveName]->setParam(QPCRModel::Model::CLIP_START,     params["CLIP_START"]);
        pState->modelList[curveName]->setParam(QPCRModel::Model::SLOPE_THR,      params["SLOPE_THR"]);
        pState->modelList[curveName]->setParam(QPCRModel::Model::SLOPE_THR_DOWN, params["SLOPE_THR_DOWN"]);
        pState->modelList[curveName]->setParam(QPCRModel::Model::MIN_CONF,       params["MIN_CONF"]);
        pState->modelList[curveName]->setParam(QPCRModel::Model::RANGE_THR,      params["RANGE_THR"]);
    }

    if(_boxAnalysis != nullptr){
        delete _boxAnalysis;
        _boxAnalysis = nullptr;
    }
    _boxAnalysis = new QMessageBox(QMessageBox::Question, "提示", "正在执行数据分析,请稍后", QMessageBox::Yes, this);
    _boxAnalysis->show();
    QTimer::singleShot(100, [this](){
        pState->calModel();
        pState->calCt();
        pState->calStandardCurve();
        pState->emitModelChanged();
        pState->emitPageChanged();
        pState->emitFilterChanged();
        pState->emitFilterResultChanged();
        pState->emitThrChanged();
        _boxAnalysis->close();
        _boxAnalysis->hide();

        // 更新Dialog内容
        QMap<QString, QMap<QString, double>>  configList;
        for(auto iter = pState->modelList.begin(); iter != pState->modelList.end(); iter ++){
            configList[iter.key()] = iter.value()->getParam();
        }_dialog_ac->component()->setParamsList(configList);
        updateACDialog();
    });


    DebugLog::funcEnd(DEBUG_CONTEXT);

}

// 从数据库读取数据、初始化组件
void DataAnalysisWindow::initData(){

    DebugLog::funcStart(DEBUG_CONTEXT);

    DebugLog::write("数据分析 - singleShot线程开启");
    pState->init();         // 执行数据计算

    _table->init(pState);
    _chartManager->init(pState);
    _actionBar->init(pState);
    _dialog_filter->init(pState);
    _dialog_as->init(pState);
    _tableGuide->init(pState);

    pState->emitModelChanged();
    pState->emitPageChanged();
    pState->emitFilterChanged();
    pState->emitFilterResultChanged();
    pState->emitThrChanged();

    DebugLog::funcEnd(DEBUG_CONTEXT);

}



// pState状态变更响应函数
void DataAnalysisWindow::on_pageChanged(){

    // 下游操作建议
    if(pState->curPage == PCRState::GUIDE_DATA || pState->curPage == PCRState::GUIDE_PLAN){
        ((QHBoxLayout*)ui->widget_2->layout())->setStretch(0, 0);
        ui->widget_3->hide();
        _table->hide();
        _chartManager->hide();
        _tableGuide->show();
        ui->pushButton_exportImage->hide();
        ui->pushButton_5->hide();
    }
    // 标准曲线
    else if(pState->curPage == PCRState::STANDARD){
        ((QHBoxLayout*)ui->widget_2->layout())->setStretch(0, 1);
        ((QHBoxLayout*)ui->widget_2->layout())->setStretch(1, 1);

        ui->widget_3->show();
        _tableGuide->hide();
        _table->show();
        _chartManager->show();
        ui->pushButton_exportImage->show();
        ui->pushButton_5->show();
    }
    // 曲线
    else{
        ((QHBoxLayout*)ui->widget_2->layout())->setStretch(0, 1);
        ((QHBoxLayout*)ui->widget_2->layout())->setStretch(1, 1);

        ui->widget_3->show();
        _tableGuide->hide();
        _table->show();
        _chartManager->show();
        ui->pushButton_exportImage->show();
        ui->pushButton_5->show();
    }
    // 切换diff时需要重新计算阈值
    pState->emitThrChanged();


}

void DataAnalysisWindow::on_filterStart(){

//#ifdef Q_OS_ANDROID
//    _dialog_filter->exec();
//#else
//    _dialog_filter->show();

//#endif
    _dialog_filter->show();
}
void DataAnalysisWindow::on_thrChanged(){
}

// 导出报告
void DataAnalysisWindow::on_pushButton_3_clicked()
{
#ifdef Q_OS_ANDROID
    // QString outpath = "/storage/emulated/0/Download/";
    DialogFileManager dfm(1);
    dfm.exec();
    QString outpath = dfm.getResult();


    if(outpath == "0" || outpath==""){
        return;
    }
    QString localPath = datao(outpath);
    DockLabel::I().show("导出成功", this);

#else


    QString saveName = pState->experimentName!="" ? pState->experimentName : QDateTime::currentDateTime().toString("yyyy-MM-dd_HH-mm-ss");

    QString filePath = QFileDialog::getSaveFileName(nullptr, "保存", "/path/to/default/"+saveName, "Xlsx files(*.xlsx)");
    if(filePath.isEmpty()|| filePath.isNull()){
        return;
    }

    if(pState->needReCalculateGuideData){
        pState->emitGuideRecalculate();
        pState->needReCalculateGuideData = false;
    }

    QString localPath = datao(filePath, 1);
    DockLabel::I().show("导出成功", this);
#endif


}

// 打印图片
void DataAnalysisWindow::on_pushButton_exportImage_clicked()
{



#ifdef Q_OS_ANDROID

    DialogFileManager dfm(1);
    dfm.exec();
    QString remotePath = dfm.getResult() + "/pic"+QDateTime::currentDateTime().toString("yyyyMMddHHmmss")+".png";
    QString localPath = SMBManager::I().SMB2Local(remotePath);
    if(localPath == "0" || localPath == "") return;
    QString filePath = localPath;


#else
    QString filePath = QFileDialog::getSaveFileName(this, "保存", "/path/to/default/directory"+QDateTime::currentDateTime().toString("yyyyMMddHHmmss")) +".png";
#endif
    if(filePath.isEmpty()||filePath.isNull()){
        return;
    }
    QPixmap p = _chartManager->_chartView->grab();
    QImage image = p.toImage();
    bool ress = image.save(filePath);

#ifdef Q_OS_ANDROID
    if(SMBManager::isSMBPath(remotePath)){
        bool res = SMBManager::I().uploadFile(remotePath, localPath);

        if(res){
            DockLabel::I().show("导出成功", this);
        }else{
            DockLabel::I().show("导出失败", this);
        }
    }else{
        if(ress){
            DockLabel::I().show("导出成功", this);
        }else{
            DockLabel::I().show("导出失败", this);
        }
    }
#endif

}


// 打印报告
void DataAnalysisWindow::on_pushButton_print_clicked()
{

    DebugLog::funcStart(DEBUG_CONTEXT);

    if(pState->curPage == PCRState::GUIDE_DATA || pState->curPage == PCRState::GUIDE_PLAN){
        QList<QTableWidget*> tableList;
        tableList.append(_tableGuide->getTable1());
        tableList.append(_tableGuide->getTable2());
        PrinterManager::printTable(tableList);
    }else{
        PrinterManager::printTable(*_table->getTable());
    }
    DebugLog::funcStart(DEBUG_CONTEXT);
    return;
}

// 全部打印
void DataAnalysisWindow::on_pushButton_printAll_clicked()
{
    QList<QTableWidget*> tableList;
    tableList.append(_table->getTable());
    tableList.append(_tableGuide->getTable1());
    tableList.append(_tableGuide->getTable2());
    PrinterManager::printTable(tableList, true);


}

// 高级配置
void DataAnalysisWindow::on_pushButton_advanceConfig_clicked()
{

    QMap<QString, QMap<QString, double>>  configList;
    for(auto iter = pState->modelList.begin(); iter != pState->modelList.end(); iter ++){
        configList[iter.key()] = iter.value()->getParam();
    }
    _dialog_ac->component()->setParamsList(configList);
    QStringList posiList;
    foreach(auto posi, pState->posiList){
        posiList.push_back(posi);
    }
    _dialog_ac->component()->setSelectableList(posiList);
    updateACDialog();

//#ifdef Q_OS_ANDROID
//    _dialog_ac->exec();
//#else
//    _dialog_ac->show();
//#endif
    _dialog_ac->show();
}

void DataAnalysisWindow::updateACDialog(){
    QVector<QStringList> fittedList;
    foreach(QString channel, pState->channelList){
        fittedList.push_back(QStringList());
        foreach(QString posi, pState->posiList){
            CurveName curve(channel, posi);
            if(pState->modelList.contains(curve) && pState->modelList[curve]->fitted()){
                fittedList.back().push_back(posi);
            }
        }
    }
    _dialog_ac->component()->setFittedList(fittedList);

}

// 颜色配置
void DataAnalysisWindow::on_pushButton_5_clicked()
{
    color=new ColorDesigner();
    color->show();
    connect(color->ui->pushButton_3,SIGNAL(clicked()),this,SLOT(RefChartColor()));
    connect(color->ui->pushButton_2,SIGNAL(clicked()),this,SLOT(NoRefChartColor()));

}

void DataAnalysisWindow::RefChartColor()
{
    if(ChartColorType==0){
        _chartManager->setColor(accessColorList,0);
    }
    else if(ChartColorType==1)
    {
        _chartManager->setColor(sampleColorList,1);
    }
    pState->emitColorChanged();

    disconnect(color->ui->pushButton_3,SIGNAL(clicked()),this,SLOT(RefChartColor()));
}

void DataAnalysisWindow::NoRefChartColor()
{
    disconnect(color->ui->pushButton_2,SIGNAL(clicked()),this,SLOT(NoRefChartColor()));
    disconnect(color->ui->pushButton_3,SIGNAL(clicked()),this,SLOT(RefChartColor()));
}


// 重新分析
void DataAnalysisWindow::on_pushButton_6_clicked()
{

    reloadData();
}
